<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Product extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->model = model("Product.Product");
        $this->TypeModel = model("Product.Type");
        $this->UnitModel = model("Product.Unit");
        $Typelist = $this->TypeModel->select();
        $Typedata = [];
        foreach ($Typelist as $k => &$v) {
            $Typedata[$v['id']] = $v['name'];
        }
        $Unitlist = $this->UnitModel->select();
        $Unitdata = [];
        foreach ($Unitlist as $k => &$v) {
            $Unitdata[$v['id']] = $v['name'];
        }
        // 标签 1-新品 2-热销 3-推荐
        $flaglist = [
            '1' => '新品',
            '2' => '热销',
            '3' => '推荐'
        ];
        // 商品状态  0 == 下架 1 == 上架
        $statusList = [
            '0' => '下架',
            '1' => '上架'
        ];
        // 商品租赁状态 1 普通商品 2 租赁商品 只能租 3 既购买也租赁的商品
        $rentSList = [
            '1' => '普通商品',
            '2' => '仅租赁商品',
            '3' => '既购买也租赁的商品',
        ];
        $this->assign([
            'flaglist' => $flaglist,
            'Typedata' => $Typedata,
            'Unitdata' => $Unitdata,
            'statusList' => $statusList,
            'rentSList' => $rentSList,
        ]);
    }
    public function index()
    {
        // $list = $this->model
        //         ->with(['type', 'unit'])
        //         ->select(); //查询数据
        // halt(collection($list)->toArray());
        // exit;
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->model
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    // 添加
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            // halt($params);
            $result = $this->model->validate('common/product/Product')->save($params);
            if ($result === FALSE) {
                if ($params['thumbs']) {
                    $thumbs = substr($params['thumbs'], 1);
                    @is_file($thumbs) && @unlink($thumbs);
                }
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }
        }
        return $this->view->fetch();
    }
    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        $this->assign("row", $row);
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            $params['id'] = $ids;
            // halt($params);
            $result = $this->model->validate('common/product/Product')->isUpdate(true)->save($params);
            if ($result === FALSE) {
                if ($params['thumbs']) {
                    $thumbs = substr($params['thumbs'], 1);
                    @is_file($thumbs) && @unlink($thumbs);
                }
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }
        }
        return $this->view->fetch();
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->column('id');
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error('没有找到该商品');
                exit;
            }
        }
        // $res = $this->model->select($ids);
        // $thumbs = array_column($res, 'thumbs');
        // foreach ($thumbs as $item) {
        //     $path = pathinfo($item, PATHINFO_DIRNAME);
        //     @is_file('.' . $item) && @unlink('.' . $item);
        //     @rmdir('.' . $path); //删除空目录
        // }
        $result = $this->model->destroy($ids);
        if ($result === FALSE) {
            $this->error($this->model->getError());
            exit;
        } else {
            $this->success();
            exit;
        }
    }

    // 回收站
    public function recyclebin()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->model
                ->onlyTrashed()
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function restore($ids = null)
    {
        $id = empty($ids) ? [] : explode(',', $ids);
        $data = [];
        foreach ($id as $item) {
            $res = $this->model->onlyTrashed()->find($item);
            if (!$res) {
                $this->error('未找到当前商品');
                exit;
            }
            $list = ['id' => $item, 'deletetime' => null];
            array_push($data, $list);
        }
        // var_dump($data);
        // exit;
        // 批量还原
        $result = $this->model->isUpdate(true)->saveAll($data);
        if ($result) {
            $this->success('还原商品成功');
            exit;
        } else {
            $this->error($this->model->getError());
            exit;
        }
    }

    // 真实删除
    public function destroy($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->onlyTrashed()->column('id');
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error('没有找到该商品');
                exit;
            }
        }
        $res = $this->model->onlyTrashed()->select($ids);
        $thumbs = array_column($res, 'thumbs');
        $result = $this->model->destroy($ids,true);
        if ($result === FALSE) {
            $this->error('删除失败');
            exit;
        } else {
            foreach ($thumbs as $item) {
                $path = pathinfo($item, PATHINFO_DIRNAME);
                @is_file('.' . $item) && @unlink('.' . $item);
                @rmdir('.' . $path); //删除空目录
            }
            $this->success('删除成功');
            exit;
        }
    }
}